package controllers

import (
	"clouds/models"
	"clouds/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
	"time"
)

type UserController struct {
	beego.Controller
}

// @router / [get]
func (c *UserController) Index() {
	c.TplName = "index.tpl"
}

type User struct {
	Code     int    `json:"code"`
	Username string `json:"username"`
	Password string `json:"password"`
}

// @router /login [get]
func (c *UserController) IndexLogin() {
	c.TplName = "login.tpl"
}

// 登录
// @Param username query string true "username"
// @Param password query string true "password"
// @router /api/login [post]
func (c *UserController) PostLogin() {
	username := c.GetString("username")
	password := c.GetString("password")

	err, user := models.Login(username, password)
	if err == orm.ErrNoRows {
		json := map[string]interface{}{"code": 500, "msg": "用户名或密码错误"}
		c.Data["json"] = json
	} else if err == nil {
		// 创建token
		maps := map[string]interface{}{"exp": time.Now().Add(time.Hour * time.Duration(1)).Unix(), "iat": time.Now().Unix()}
		tokenString := utils.NewToken(username, maps)
		setTokenErr := models.SetToken(user.Id, tokenString)

		// 获取菜单
		menus := models.GetUserMenus(user.Id)
		//fmt.Println(menus)

		if setTokenErr != nil {
			fmt.Println(setTokenErr)
		}
		// 序列化用户信息
		userInfo := map[string]interface{}{
			"userId": user.Id,
			"userName": user.UserName,
			"password": user.Password,
		}
		json1 := map[string]interface{}{"code": 200, "msg": "",
			"data": map[string]interface{}{"userInfo": userInfo, "token": tokenString, "menus": menus}}

		c.Data["json"] = json1
	} else {
		c.Data["json"] = map[string]interface{}{"code": 500, "msg": err}
	}
	c.ServeJSON()
}

// @router /success [get]
func (c *UserController) LoginSuccess() {
	c.TplName = "login_success.tpl"
}

// @router /register [get]
func (c *UserController) IndexRegister() {
	c.TplName = "register.tpl"
}

// 注册
// @Param username query string true "username"
// @Param password query string true "password"
// @router /register [post]
func (c *UserController) PostRegister() {
	username := c.GetString("username")
	password := c.GetString("password")

	o := orm.NewOrm()
	profile := models.Profile{Age: 28, Sex: 1, Info: "很不错的人"}
	profileId, err1 := o.Insert(&profile)
	profile.Id = int(profileId)
	user := models.User{UserName: username, Password: password, Profile: &profile}
	userId, err := o.Insert(&user)

	if err != nil && err1 != nil {
		fmt.Println("注册失败")
		fmt.Println(err, err1)
		c.Data["json"] = map[string]interface{}{"code": 500, "msg": "注册失败"}
	} else {
		fmt.Println("注册成功！")
		fmt.Println(userId)
		c.Data["json"] = map[string]interface{}{"code": 200, "msg": "注册成功"}
	}
	c.ServeJSON()
}

// 用户管理
// @router /userSystem [get]
func (c *UserController) UserSystem() {
	users := []models.User{}
	o := orm.NewOrm()
	num, err := o.QueryTable("user").RelatedSel().All(&users)
	if num == 0 {
		println("暂无数据")
	} else if err != nil {
		println("查询失败")
	} else {
		c.Data["users"] = users
		c.Data["num"] = num
	}
	//for _, row := range users {
	//	fmt.Println(row)
	//}

	c.TplName = "user_system.tpl"
}

// 删除用户
// @Param userId query string true "userId"
// @router /deleteuser	[get]
func (c *UserController) DeleteUser() {
	userId := c.GetString("userId")
	fmt.Println(userId)
	userIdInt, _ := strconv.Atoi(userId)
	user := models.User{Id: userIdInt}
	o := orm.NewOrm()
	_, err := o.Delete(&user)
	if err != nil {
		c.Data["msg"] = "删除失败"
	} else {
		c.Data["msg"] = "删除成功"
	}
	fmt.Println(c.Data["msg"])
	c.Redirect("/userSystem", 302)
}
